package com.baizhi.controller;


import com.baizhi.entity.Euser;
import com.baizhi.service.EuserService;

import com.baizhi.util.CreateValidateCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("euser")
public class EuserController {

    private static final Logger log = LoggerFactory.getLogger(EuserController.class);
    @Autowired
    private EuserService euserService;



    @RequestMapping("image")
    public void writeImage(HttpSession session , HttpServletResponse response) throws IOException {
        CreateValidateCode cvc = new CreateValidateCode();
        String code = cvc.getCode();
        session.setAttribute("code",code);
        ServletOutputStream out = response.getOutputStream();
        cvc.write(out);
    }





    @RequestMapping("login")
    public String login(Euser euser, String ucode, HttpServletRequest request){
        int result = euserService.queryEuser(euser);
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        log.debug("111111"+ucode);
        if (code.equals(ucode) == false) {
            session.setAttribute("error", "验证码错误");
            return "view/login";
        } else {
            if (result == 1) {
                session.setAttribute("username", euser.getUsername());
                return "redirect:/emp/ShowAllEmp";
            } else if (result == 2) {
                session.setAttribute("error", "您的账号有误");
                return "view/login";
            } else {
                session.setAttribute("error", "您的密码有误");
                return "view/login";
            }
        }
    }

    //安全退出
    @RequestMapping("exit")
    public String exit(HttpServletRequest request){
        request.getSession().removeAttribute("username");
        request.getSession().removeAttribute("error");
        request.getSession().invalidate();
        return "view/login";
    }





}
